package com.adkun.community.event;

import com.adkun.community.entity.DiscussPost;
import com.adkun.community.entity.Event;
import com.adkun.community.entity.Message;
import com.adkun.community.service.DiscussPostService;
import com.adkun.community.service.ElasticsearchService;
import com.adkun.community.service.MessageService;
import com.adkun.community.util.CommunityUtil;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;

import static com.adkun.community.util.CommunityConstants.*;

@Component
@Slf4j
public class EventConsumer {

    @Autowired
    private MessageService messageService;

    @Autowired

    private ElasticsearchService elasticsearchService;

    @Autowired
    private DiscussPostService discussPostService;

    @Value("${wk.image.storage}")
    public String wkImageStorage;

    @Value("${wk.image.command}")
    public String wkImageCommand;

    @Value("${qiniu.key.access}")
    private String accessKey;

    @Value("${qiniu.key.secret}")
    private String secretKey;

    @Value("${qiniu.bucket.share.name}")
    private String shareBucketName;

    private final ThreadPoolTaskScheduler taskScheduler;

    public EventConsumer(ThreadPoolTaskScheduler taskScheduler) {
        this.taskScheduler = taskScheduler;
    }

    /**
     * 消费分享事件
     *
     * @param record
     */
    @KafkaListener(topics = {TOPIC_SHARE})
    public void handleShareMessage(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            log.error("消息内容为空");
            return;
        }
        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            log.error("消息格式错误！");
            return;
        }

        String htmlUrl = (String) event.getData().get("htmlUrl");
        String fileName = (String) event.getData().get("fileName");
        String suffix = (String) event.getData().get("suffix");

        String cmd = wkImageCommand + " --quality 75 " + htmlUrl
                + " " + wkImageStorage + "/" + fileName + suffix;
        try {
            // 这个命令是比较耗时的，该命令会在下一句后面执行完。
            Runtime.getRuntime().exec(cmd);
            log.info("生成长图成功！" + cmd);
        } catch (IOException e) {
            log.error("生成长图失败！" + e.getMessage());
        }

        // 启动一个定时器，看文件是否生成了
        // 该定时器是谁抢到了消息谁启动。（消息队列的性质）
        // 一旦图片生成了就上传到七牛云
        UploadTask task = new UploadTask(fileName, suffix);
        // 该定时器之后要停止执行
        Future future = taskScheduler.scheduleAtFixedRate(task, 500);
        task.setFuture(future);
    }

    class UploadTask implements Runnable {

        /**
         * 文件名称
         */
        private String fileName;

        /**
         * 文件后缀
         */
        private String suffix;

        /**
         * 启动任务的返回值
         */
        private Future future;

        /**
         * 开始时间
         * 上传30秒停止定时器
         */
        private long startTime;

        /**
         * 上传次数
         * 上传3次停止
         */
        private int uploadTimes;

        public UploadTask(String fileName, String suffix) {
            this.fileName = fileName;
            this.suffix = suffix;
            this.startTime = System.currentTimeMillis();
        }

        public void setFuture(Future future) {
            this.future = future;
        }

        @Override
        public void run() {
            // 该方法要将定时器结束执行
            // 有可能定时器无法结束，如图片上传失败

            // 情况1 生成失败
            if (System.currentTimeMillis() - startTime > 30000) {
                log.error("执行时间过长！终止任务：" + fileName);
                future.cancel(true);
                return;
            }
            // 情况2 上传失败
            if (uploadTimes > 3) {
                log.error("上传次数过多，终止任务：" + fileName);
                future.cancel(true);
                return;
            }

            String path = wkImageStorage + "/" + fileName + suffix;
            File file = new File(path);
            if (file.exists()) {
                log.info(String.format("开始第%d次上传[%s]", ++uploadTimes, fileName));
                // 设置响应信息
                StringMap policy = new StringMap();
                policy.put("returnBody", CommunityUtil.getJSONString(0));
                // 生成上传凭证
                Auth auth = Auth.create(accessKey, secretKey);
                String uploadToken = auth.uploadToken(shareBucketName, fileName, 3600, policy);
                // 指定上传机房
                UploadManager manager = new UploadManager(new Configuration(Zone.zone2()));
                try {
                    // 开始上传图片
                    Response response = manager.put(
                            path, fileName, uploadToken, null, "image/" + suffix, false
                    );
                    // 处理响应结果
                    JSONObject json = JSONObject.parseObject(response.bodyString());
                    if (json == null || json.get("code") == null || !json.get("code").toString().equals("0")) {
                        // 返回的数据要么是空，要么没有code，要么code不对，就上传失败。
                        log.info("第%d次上传失败[%s]", uploadTimes, fileName);
                    } else {
                        log.info("第%d次上传成功[%s]", uploadTimes, fileName);
                        future.cancel(true);
                    }

                } catch (QiniuException e) {
                    log.info(String.format("第%d次上传失败[%s]", uploadTimes, fileName));
                }
            } else {
                log.info("等待图片生成[" + fileName + "]");
            }
        }
    }

    /**
     * 评论事件
     *
     * @param record
     */
    @KafkaListener(topics = {TOPIC_COMMENT, TOPIC_LIKE, TOPIC_FOLLOW})
    public void handleCommentMessage(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            log.error("消息内容为空！");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            log.error("消息格式错误！");
            return;
        }

        // 发送站内通知
        Message message = new Message();
        message.setFromId(SYSTEM_USER_ID);
        message.setToId(event.getEntityUserId());
        message.setConversationId(event.getTopic());
        message.setCreateTime(new Date());

        Map<String, Object> content = new HashMap<>();
        content.put("userId", event.getUserId());
        content.put("entityType", event.getEntityType());
        content.put("entityId", event.getEntityId());

        if (!event.getData().isEmpty()) {
            for (Map.Entry<String, Object> entry : event.getData().entrySet()) {
                content.put(entry.getKey(), entry.getValue());
            }
        }

        message.setContent(JSONObject.toJSONString(content));
        messageService.addMessage(message);
    }

    // 消费发帖事件

    /**
     * 消费发帖事件
     *
     * @param record
     */
    @KafkaListener(topics = {TOPIC_PUBLISH})
    public void handlePublishMessage(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            log.error("消息内容为空");
            return;
        }
        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            log.error("消息格式错误！");
            return;
        }

        // 从事件消息得到帖子ID，查到帖子，存到ES服务器
        DiscussPost post = discussPostService.findDiscussPostById(event.getEntityId());
        elasticsearchService.saveDiscussPost(post);
    }

    /**
     * 删帖事件
     *
     * @param record
     */
    @KafkaListener(topics = {TOPIC_DELETE})
    public void handleDeleteMessage(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            log.error("消息内容为空");
            return;
        }
        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            log.error("消息格式错误！");
            return;
        }

        elasticsearchService.deleteDiscussPost(event.getEntityId());
    }


}
